<template>
  <div class="babyRadio-container" :style="`min-height: ${height || 40}px`">
    <div
      v-for="(item, index) in items"
      :key="item.value"
      class="item"
      :class="{
        active: item.active,
        fixWidth: !!fixWidth,
        anotherStyle: anotherStyle
      }"
      :style="
        `margin-right:${marginRight}%;margin-bottom:${marginBottom}px;min-width:${
          fixWidth ? fixWidth + 'px' : 'auto'
        }`
      "
      @click="toogle(index)"
    >
      {{ item.label }}
    </div>
    <slot></slot>
  </div>
</template>
<script>
export default {
  props: {
    items: [Array],
    height: [Number],
    resVal: {},
    marginRight: {
      type: Number,
      require: false,
      default: 10
    },
    marginBottom: {
      type: Number,
      require: false,
      default: 0
    },
    fixWidth: {
      type: Number,
      require: false,
      default: 0
    },
    anotherStyle: {
      type: Boolean,
      require: false,
      default: false
    }
  },
  watch: {
    resVal: {
      handler(v) {
        let i = 0;
        this.items.forEach((it, index) => {
          if (v === it.value) {
            i = index;
          }
        });
        this.toogle(i);
      },
      immediate: true
    }
  },
  methods: {
    toogle(index) {
      if (this.items.length === 0) return;
      const newItems = JSON.parse(JSON.stringify(this.items));
      newItems.forEach(it => {
        it.active = false;
      });
      newItems[index].active = true;
      this.$emit('update:items', newItems);
      this.$emit('update:resVal', newItems[index].value);
    }
  }
};
</script>
<style lang="scss" scoped>
.babyRadio-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  flex: 1;
  .item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 25px;
    border-radius: 15px;
    padding: 0 20px;
    border: 1px solid #b3b3b3;
    line-height: 25px;
    color: #333;
    cursor: pointer;
    &.active {
      background-color: #ffb03e;
      border: 1px solid #ffb03e;
      color: #fff;
    }
    &:last-child {
      margin-right: 0 !important;
    }
  }
  .anotherStyle {
    border: 1px solid #827d7d;
    color: #827d7d;
  }
  .fixWidth {
    padding: 0;
  }
}
</style>
